define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            $(".btn-add").data('area',["100%",'100%']);
            $(".btn-edit").data('area',["100%",'100%']);
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'factory/sales/index' + location.search,
                    // add_url: 'factory/sales/add',
                    // edit_url: 'factory/sales/edit',
                    del_url: 'factory/sales/del',
                    multi_url: 'factory/sales/multi',
                    table: 'sales_slip',
                }
            });

            var table = $("#table");
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                dblClickToEdit: false,
                sortName: 'id',
                rowStyle:function(row, index){
                    if (row.ystatus == 6 ||row.ystatus == 7 || row.ystatus == 8) {
                        return{
                            css:{
                                color:'red'
                            }
                        }
                    }else{
                        return{}
                    }
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),class: 'sid'},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'number', title: __('Number')},
                        {field: 'sl_number', title: __('销售单号'), formatter: Controller.api.formatter.number},
                        {field: 'ccompany', title: __('Nickname')},
                        {field: 'snickname', title: __('供应商')},
                        // {field: 'name', title: __('Name'),searchList: $.getJSON(Config.this_url+"/config/zaxconfig?states=1")},
                        // {field: 'status', title: __('Status')},
                        // {field: 'deliverytime', title: __('Deliverytime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},

                        // {field: 'abstract', title: __('Abstract')},
                        // {field: 'admin_id', title: __('Admin_id')},
                        // {field: 'group_id', title: __('Group_id')},
                        {field: 'sales_num', title: __('销售数量'),operate:false},
                        {field: 'actual_cost', title: __('订单金额'),operate:false},
                        {field: 'unit_actual_cost', title: __('采购金额'),operate:false},
                        {field: 'unit_allfare', title: __('采购运费'),operate:false},
                        {field: 'operator', title: __('Operator')},
                        {field: 'company', title: __('Company')},
                        {field: 'house_name', title: __('运营区域'),operate:false},
                        {field: 'status', title: __('Status'),searchList: $.getJSON(Config.this_url+"/config/zaxconfig?states=16")},
                        {
                            field: 'goods_name', title: __('商品名称'), visible: false
                        },
                        {field: 'explain', title: __('Explain'),operate:false,class: 'explain',cellStyle:function (value, row, index) {
                                return {
                                    css: {
                                        "min-width": "100px",
                                        "white-space": "nowrap",
                                        "text-overflow": "ellipsis",
                                        "overflow": "hidden",
                                        "max-width": "120px"
                                    }
                                }
                            }},
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            buttons: [
                                {
                                    name: 'examine',
                                    title: __('采购'),
                                    classname: 'btn btn-xs btn-success  btn-click editstatus',
                                    icon: 'fa fa-shopping-cart',
                                    // font-size:80,
                                    hidden:function(row){
                                        if(row.ystatus != 1){
                                            return true;
                                        }
                                    },
                                    click: function(data){
                                        var sid =$(this).parents('tr').find('.sid').html()


                                        var url = Config.this_url+'/factory/sales/purchase?ids='+sid
                                        layer.open({
                                            type: 2, // 1-在content中写html代码， 2-在content中写src路径
                                            area: ['100%', '100%'],
                                            title: "采购",
                                            content: url,
                                            // content: Config.this_url+'/purchase/requisition',
                                        })
                                    }},
                                {
                                    name: 'examine',
                                    title: __('事后修正'),
                                    classname: 'btn btn-xs btn-success  btn-click editstatus',
                                    icon: 'fa fa-pencil-square-o',
                                    // font-size:80,
                                    hidden:function(row){
                                        if(row.ystatus != 5){
                                            return true;
                                        }
                                    },
                                    click: function(data){
                                        var sid =$(this).parents('tr').find('.sid').html()


                                        var url = Config.this_url+'/factory/sales/afterpurchase?ids='+sid
                                        layer.open({
                                            type: 2, // 1-在content中写html代码， 2-在content中写src路径
                                            area: ['100%', '100%'],
                                            title: "采购事后修正",
                                            content: url,
                                            // content: Config.this_url+'/purchase/requisition',
                                        })
                                    }},
                                {
                                    name: 'detail',
                                    title: __('销售单审核'),
                                    classname: 'btn btn-xs btn-danger  btn-click editstatus',
                                    icon: 'fa fa-random',
                                    // font-size:80,
                                    hidden:function(row){
                                        if(row.ystatus != 2){
                                            return true;
                                        }
                                    },
                                    click: function(data){
                                        var sid =$(this).parents('tr').find('.sid').html()


                                        var url = Config.this_url+'/factory/sales/detail?ids='+sid
                                        layer.open({
                                            type: 2, // 1-在content中写html代码， 2-在content中写src路径
                                            area: ['80%', '90%'],
                                            title: "审核",
                                            content: url,
                                            // content: Config.this_url+'/purchase/requisition',
                                        })
                                    }},
                                {
                                    name: 'deliver',
                                    title: __('发货'),
                                    classname: 'btn btn-xs btn-success  btn-click editstatus',
                                    icon: 'fa fa-car',
                                    // font-size:80,
                                    hidden:function(row){
                                        if(row.ystatus != 3){
                                            return true;
                                        }
                                    },
                                    click: function(data){
                                        var sid =$(this).parents('tr').find('.sid').html()
                                        var url = Config.this_url+'/factory/sales/examine2?ids='+sid
                                        layer.open({
                                            type: 2, // 1-在content中写html代码， 2-在content中写src路径
                                            area: ['80%', '90%'],
                                            title: "发货凭证",
                                            content: url,
                                            // content: Config.this_url+'/purchase/requisition',
                                        })
                                    }},
                                {
                                    name: 'deliver',
                                    title: __('到货'),
                                    classname: 'btn btn-xs btn-success  btn-click editstatus',
                                    icon: 'fa fa-handshake-o',
                                    // font-size:80,
                                    hidden:function(row){
                                        if(row.ystatus != 4){
                                            return true;
                                        }
                                    },
                                    click: function(data){
                                        var sid =$(this).parents('tr').find('.sid').html()
                                        var url = Config.this_url+'/factory/sales/examine3?ids='+sid
                                        layer.open({
                                            type: 2, // 1-在content中写html代码， 2-在content中写src路径
                                            area: ['80%', '90%'],
                                            title: "到货凭证",
                                            content: url,
                                            // content: Config.this_url+'/purchase/requisition',
                                        })
                                    }},
                                {
                                    name: 'printsale',
                                    title: __('打印销售单'),
                                    classname: 'btn btn-xs btn-warning btn-click editstatus',
                                    icon: 'fa fa-print',
                                    hidden:function(row){

                                    },
                                    click: function(data){
                                        var sid =$(this).parents('tr').find('.sid').html()
                                        window.open(Config.this_url+'/factory/sales/printsale?ids='+sid)
                                    }},
                                {
                                    name: 'printpurche',
                                    title: __('打印采购单'),
                                    classname: 'btn btn-xs btn-warning btn-click editstatus',
                                    icon: 'fa fa-print',
                                    hidden:function(row){

                                    },
                                    click: function(data){
                                        var sid =$(this).parents('tr').find('.sid').html()
                                        window.open(Config.this_url+'/factory/sales/printpurche?ids='+sid)
                                    }},

                            ],
                            events: Table.api.events.operate,
                            formatter: function (value, row, index) {
                                var that = $.extend({}, this);
                                var table = $(that.table).clone(true)
                                // $(table).data("operate-del", null); // 列表页面隐藏 .编辑operate-edit - 删除按钮operate-del
                                // console.log(row)
                                if(row['ystatus'] != 1){
                                    $(table).data("operate-edit", null);// 列表页面隐藏 .编辑operate-edit - 删除按钮operate-del
                                    $(table).data("operate-del", null);// 列表页面隐藏 .编辑operate-edit - 删除按钮operate-del
                                }
                                that.table = table;
                                return Table.api.formatter.operate.call(that, value, row, index);
                            }}
                    ]
                ]
            });
            $('body').on('mouseenter','.explain',function () {
                if (this.offsetWidth < this.scrollWidth) {
                    var that = this;
                    var text = $(this).text();
                    layer.tips(text, that,{
                        tips: 1,
                        time: 2000         //设置显示时间
                    });
                }
            })
            //当表格数据加载完成时
            table.on('load-success.bs.table', function (e, data) {
                //这里可以获取从服务端获取的JSON数据
                // console.log(data);
                //这里我们手动设置底部的值
                // $("#num").text(data.num);
                // $("#price").text(data.price);
                $('#getgather').click()
            });
            $('.commonsearch-table').on('click','.btn-success',function () {
                $('#getgather').click()
            })
            $('#getgather').click(function () {
                // layer.load(1);
//此处演示关闭
                that = $(this)
                var data = $('form').serialize();
                var url = Config.this_url+'/factory/sales/getcount';
                $.post(url,data,function (res) {
                    that.find('#num').html(res.num)
                    that.find('#price').html(res.price)
                })
                // setTimeout(function(){
                //     layer.closeAll('loading');
                // }, 2000);
            })



            $('table').on('dblclick','td',function(){

                // if($(this).parents('tr').find('.btn-editone').length >0){
                //     return  false;
                // }

                var sid = $(this).parents('tr').find('.sid').html()
                var url = Config.this_url+'/factory/sales/detail?ids='+sid
                layer.open({
                    type: 2, // 1-在content中写html代码， 2-在content中写src路径
                    area: ['100%', '100%'],
                    title: "直发单详情",
                    content: url,
                    // content: Config.this_url+'/purchase/requisition',
                })
            });
            table.on('post-body.bs.table',function () {
                $(".btn-editone").data('area',["100%",'100%']);
            })
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            $(".btn-add").click(function () {

                // if($('#c-storehouse_id').val()== 0 ){
                //     layer.msg('未选中出库仓库')
                //     return false;
                // }
                // console.log($('#c-storehouse_id').val())
                layer.open({
                    type: 2, // 1-在content中写html代码， 2-在content中写src路径
                    area: ['70%', '90%'],
                    title: "选择商品",
                    content: 'seach?house_id='+$('#c-storehouse_id').val(),
                })
            })
            var customer_id = 0;
            $(document).on("change", "#c-customer_id", function () {
                var cid = $('#c-customer_id').val()
                if(cid == ''){
                    return  false;
                }
                if(cid == customer_id){
                    return false;
                }
                customer_id = cid;
                var url = Config.this_url+'/customer/customer/detail?ids='+cid
                $.post(url,{},function (res) {
                    $('#default_mobile').val(res.mobile)
                    $('#default_address').val(res.address)
                    $('#default_contacts').val(res.nickname)
                })
            })
            Controller.api.bindevent();
        },
        edit: function () {
            // $(".btn-add").click(function () {
            //     layer.open({
            //         type: 2, // 1-在content中写html代码， 2-在content中写src路径
            //         area: ['70%', '90%'],
            //         title: "选择商品",
            //         content: Config.this_url+'/sales/slip/seach',
            //     })
            // })
            $(".btn-add").click(function () {

                if($('#c-storehouse_id').val()== 0 ){
                    layer.msg('未选中出库仓库')
                    return false;
                }
                layer.open({
                    type: 2, // 1-在content中写html代码， 2-在content中写src路径
                    area: ['70%', '90%'],
                    title: "选择商品",
                    content: Config.this_url+'/sales/slip/seach?house_id='+$('#c-storehouse_id').val(),
                })
            })
            var customer_id = 0;
            $(document).on("change", "#c-customer_id", function () {
                var cid = $('#c-customer_id').val()
                if(cid == ''){
                    return  false;
                }
                if(cid == customer_id){
                    return false;
                }
                customer_id = cid;
                var url = Config.this_url+'/customer/customer/detail?ids='+cid
                $.post(url,{},function (res) {
                    $('#default_mobile').val(res.mobile)
                    $('#default_address').val(res.address)
                    $('#default_contacts').val(res.nickname)
                })
            })
            Controller.api.bindevent();
        },
        detail:function(){
            $('.cancelbill').click(function () {
                var url =  Config.this_url+'/factory/sales/cancelbill'+location.search
                layer.prompt({title: '输入红冲原因', formType: 2}, function(pass, index){
                    if(pass == ''){
                        layer.msg('不能为空');
                        return false;
                    }
                    $.post(url,{reason:pass},function (res) {
                        layer.msg(res.msg)
                        if(res.code == 1){
                            layer.close(index);
                            setTimeout(function () {
                                location.reload();
                            }, 800);
                            window.parent.$(".toolbar .btn-refresh").trigger('click');
                        }
                    })
                });
            })

            $('.btn-end').click(function () {
                    var ids = $(this).data('id');
                    layer.confirm('是否中止该商品？', {
                        btn: ['确定','取消'] //按钮
                    }, function(){
                        var url = Config.this_url +'/sales/slip/stop?ids='+ids
                        $.post(url,{},function (res) {
                            layer.msg(res.msg)
                            if(res.code == 1){
                                setInterval(function () {
                                    window.location.reload()
                                },1000)
                            }
                        })
                    })
            })
            Controller.api.bindevent();
        },
        examine2:function(){
            Controller.api.bindevent();
        },
        examine3:function(){
            Controller.api.bindevent();
        },
        purchase:function(){
            Controller.api.bindevent();
        },
        afterpurchase:function(){
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {
                number: function (value, row, index) {
                    //这里手动构造URL
                    url = "discuss?" + this.field + "=" + value;
                    url = "sales/checkout?slip.number=" + value;

                    //方式一,直接返回class带有addtabsit的链接,这可以方便自定义显示内容
                    return '<a href="' + url + '" class="label label-success addtabsit" title="' + __("Search %s", value) + '">' + __( value) + '</a>';

                    //方式二,直接调用Table.api.formatter.addtabs
                    return Table.api.formatter.addtabs(value, row, index, url);
                }
            }
        },
        seach:function(){
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'goods/goods/specs',
                    table: '',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                pageSize:15,
                // searchFormVisible: true,
                searchFormTemplate: 'customformtpl',
                columns: [
                    [
                        // {checkbox: true,operate:false},
                        {field: 'id', title: 'ID', operate: false,class:'sid'},
                        {field: 'title', title: __('title'),  operate: false},
                        {field: 'place_origin', title: __('place_origin'), formatter: Table.api.formatter.search},
                        {field: 'number', title: __('number')},
                        {field: 'unit', title: __('unit'), align: 'left'},
                        {field: 'specs', title: __('specs')},
                        {field: 'stock', title: __('stock')},
                        {field: 'createtime', title: __('Create time'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange', sortable: true},
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            buttons: [
                                {
                                    name: 'returnorder',
                                    title: __('选中'),
                                    classname: 'btn btn-xs btn-success btn-click editstatus',
                                    icon: 'fa fa-fighter-jet',
                                    hidden:function(row){
                                        // if(row.status != '审核'){
                                        //     return true;
                                        // }
                                    },
                                    click: function(data){
                                        var sid =$(this).parents('tr').find('.sid').html()
                                        $(this).attr('style','display:none')
                                        parent.getrequisition(sid);
                                    }}
                            ],
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });
            $('table').on('dblclick','td',function(){

                var sid =$(this).parents('tr').find('.sid').html()
                parent.getrequisition(sid);
                var index = parent.Layer.getFrameIndex(window.name);
                parent.Layer.close(index);

            });

            // $(document).scroll(function() {
            //     if ($(document).height()-$(document).scrollTop()-window.innerHeight == 0) {
            //         console.log()
            //         if($('.pagination').find('.active').parents('div').css('display') == 'none'){
            //
            //         }else{
            //             setTimeout(function () {
            //                 $('.pagination').find('.active').next().click()
            //                 $('html,body').animate({scrollTop:0},1000);//回到顶端
            //             },500)
            //         }
            //
            //
            //         // console.log(1)
            //     } else {
            //         // console.log(2)
            //     }
            // })
            // $(window).scroll(function ()
            // {
            //     var st = $(this).scrollTop();
                // console.log(st)
                // if(st == 0){
                //     if($('.pagination').find('.active').parents('div').css('display') == 'none'){
                //
                //     }else{
                //         setTimeout(function () {
                //             $('.pagination').find('.active').prev().click()
                //             $('html,body').animate({scrollTop:0},1000);//回到顶端
                //         },500)
                //     }
                // }
            // });
            $('div.mousewheel_example')
                .bind('mousewheel', function(event, delta) {
                    var dir = delta > 0 ? 'Up' : 'Down',
                        vel = Math.abs(delta);
                    $(this).text(dir + ' at a velocity of ' + vel);
                    return false;
                });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },

    };
    return Controller;
});